package inter.authorization.resolvers;

import inter.authorization.annotation.CurrentAppUser;
import inter.config.Constants;
//import inter.domain.User;
//import inter.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

/**
 * 增加方法注入，将含有CurrentAppUser注解的方法参数注入当前登录用户
 * 
 * @see inter.authorization.annotation.CurrentAppUser
 * @author Max
 * @date 2016/10/24.
 */
@Component
public class CurrentAppUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

	/**
	 * 
	 * @Autowired private UserRepository userRepository;
	 * 
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		// 如果参数类型是User并且有CurrentUser注解则支持
		/*
		 * if (parameter.getParameterType().isAssignableFrom(User.class) &&
		 * parameter.hasParameterAnnotation(CurrentAppUser.class))
		 */
		if (parameter.hasParameterAnnotation(CurrentAppUser.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		// 取出鉴权时存入的登录用户Id
		String currentAppId = (String) webRequest.getAttribute(Constants.CURRENT_APP_ID,
				RequestAttributes.SCOPE_REQUEST);
		if (currentAppId != null) {
			// 从数据库中查询并返回
			//return userRepository.findOne(currentUserId);
		}
		throw new MissingServletRequestPartException(Constants.CURRENT_APP_ID);
	}
}